<template>
    <div class="form_box">
      <div class="header"></div>
      <a-spin :spinning="spinning">
      <a-form
        :model="state.formState"
        layout="vertical"
        name="basic"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <a-form-item
          label="任务名称"
          name="pu_title"
          :rules="[
            { required: true, message: '请输入任务名称', trigger: 'change' },
          ]"
        >
          <a-input
            v-model:value="state.formState.pu_title"
            placeholder="请输入任务名称"
            show-count
            :maxlength="15"
          />
        </a-form-item>
        <a-form-item label="信息图片（包含订单，联系方式等重要信息 不超过五张）" name="imgList"   :rules="[
            { required: true, validator: validateImg, trigger: 'change' },
          ]">
          <upload
            @uploadRes="uploadRes"
            :maxCount="5"
            :img-list="state.imgList"
            ref="uploadRef"
          ></upload>
        </a-form-item>
        <a-form-item
          label="平台"
          name="pu_platform"
          has-feedback
          :rules="[{ required: true, message: '请选择平台', trigger: 'change' }]"
        >
          <a-select
            v-model:value="state.formState.pu_platform"
            :options="state.platformData"
            size="middle"
            placeholder="请选择平台"
            :field-names="{ label: 'name', value: 'id' }"
          ></a-select>
        </a-form-item>
        <a-form-item
          label="地区"
          has-feedback
          name="newAddress"
          :rules="[{ required: true, message: '请填写地区', trigger: 'change' }]"
        >
          <a-cascader
            :show-search="{ filter }"
            v-model:value="state.formState.newAddress"
            :options="proxyCityData"
            placeholder="请选择任务派往地区"
            :fieldNames="{ label: 'name', value: 'code', children: 'children' }"
          />
        </a-form-item>
        <a-form-item label="茶水费（会有人更快帮助哦 最多不超过1000）" name="income">
          <a-input
            v-model:value="state.formState.pu_tip"
            placeholder="请输入费用"
            type="number"
          />
        </a-form-item>
        <a-form-item
          label="结束时间"
          name="newTime"
          :rules="[
            { required: true, validator: validateNewTime, trigger: 'change' },
          ]"
        >
          <a-config-provider :locale="zhCN">
            <a-date-picker
              v-model:value="state.formState.newTime"
              format="YYYY-MM-DD"
              :disabled-date="disabledDate"
              :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }"
            />
          </a-config-provider>
        </a-form-item>
        <a-form-item
          label="备注信息"
          name="pu_description"
          :rules="[
            { required: true, message: '请描述详细信息', trigger: 'change' },
          ]"
        >
          <a-textarea
            v-model:value="state.formState.pu_description"
            placeholder="请描述详细信息"
            :rows="4"
            show-count
            :maxlength="80"
          />
        </a-form-item>
        <a-form-item>
          <div style="text-align: center">
            <a-button type="primary" html-type="submit" size="large" block>
              发布
            </a-button>
          </div>
        </a-form-item>
      </a-form>
      </a-spin>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { reactive, getCurrentInstance, onMounted, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { message } from 'ant-design-vue';
  import dayjs, { Dayjs } from 'dayjs';
  import { getPublishDetails, editFun } from '@/api/mutualaid/index';
  import upload from '../../../components/upload/index.vue';
  import publishListMethod from '@/hooks/type/index';
  import cityData from '@/data/city/index';
  import zhCN from 'ant-design-vue/es/locale/zh_CN';
  import 'dayjs/locale/zh-cn';
  dayjs.locale('en');
  
  const key = '加载中';
  const router = useRouter();
  const appCurrent = getCurrentInstance();
  const flidata = reactive({
    path: 'avatar',
  });
  const spinning = ref<boolean>(true);
  interface UploadRefType {
    initializeFileList: () => void;
  }
  const uploadRef = ref<UploadRefType | null>(null);
  
  interface FormState {
    id: string;
    pu_userId: string;
    pu_title: string;
    pu_order_screenshot: string;
    pu_tip: number | string;
    pu_finish_time: Dayjs | string;
    pu_receiver: number | string;
    pu_type: number | string;
    pu_description: number | string;
    pu_platform: string;
    pu_province_id: any;
    pu_city_id: string;
    pu_district_id: string;
    newAddress: any;
    newTime: Dayjs | null; // 添加 newTime 到表单模型
  }
  
  const state = reactive({
    platformData: [] as any[],
    formState: {
      id: '',
      pu_userId: JSON.parse(window.localStorage.getItem('userInfo') || '{}').id || {},
      pu_title: '',
      pu_order_screenshot: '',
      pu_platform: '',
      pu_tip: '',
      pu_receiver: 0,
      pu_finish_time: '',
      pu_description: '',
      pu_type: 1,
      pu_province_id: '',
      pu_city_id: '',
      pu_district_id: '',
      newAddress: [],
      newTime: null, // 初始化 newTime
    } as FormState,
    newAddress: [] as string[],
    imgList: [] as string[],
  });
  
  const proxyCityData = cityData;
  
  const filter = (inputValue: string, path: any) => {
    return path.some((option: any) => option.name.indexOf(inputValue) > -1);
  };
  
  const uploadRes = (file: never[]) => {
    state.formState.pu_order_screenshot = file.toString();
  };
  
  const validateNewTime = (rule: any, value: Dayjs) => {
    if (!value) {
      return Promise.reject('请选择结束时间');
    }
    return Promise.resolve();
  };
  const validateImg = (rule: any, value: string) => {
    if (state.formState.pu_order_screenshot.split(',').length === 0 || state.formState.pu_order_screenshot.split(',').length > 5){
      return Promise.reject('请上传图片并且不能超过5张');
    }
    return Promise.resolve();
  };
  const onFinish = async (values: any) => {
    message.loading({ content: 'Loading...', key });
    const res = await editFun({
      id: state.formState.id,
      pu_userId: state.formState.pu_userId,
      pu_title: state.formState.pu_title,
      pu_order_screenshot: state.formState.pu_order_screenshot,
      pu_tip: state.formState.pu_tip,
      pu_finish_time: state.formState.pu_finish_time,
      pu_receiver: state.formState.pu_receiver,
      pu_type: state.formState.pu_type,
      pu_province_id: state.formState.newAddress[0],
      pu_city_id: state.formState.newAddress[1],
      pu_district_id: state.formState.newAddress[2],
      pu_platform: state.formState.pu_platform,
      pu_description: state.formState.pu_description,
    });
    if (res.data.code != 0) {
      return message.error({
        content: res.data.msg,
        key,
        duration: 2,
      });
    }
    message.success({
      content: '编辑成功',
      key,
      duration: 2,
    });
    router.go(-1);
  };
  
  const onFinishFailed = (errorInfo: any) => {
    message.loading({ content: 'Loading...', key });
    setTimeout(() => {
      message.error({ content: '发布失败!', key, duration: 2 });
    });
  };
  
  onMounted(async () => {
    const res = await getPublishDetails({
      id: router.currentRoute.value.query.id,
    });
    state.formState = res.data.data;
    state.formState.pu_tip = parseInt(res.data.data.pu_tip);
  
    const {
      pu_finish_time,
      pu_province_id,
      pu_city_id,
      pu_district_id,
      pu_order_screenshot,
    } = res.data.data as FormState;
    state.formState.newTime = dayjs(pu_finish_time, 'YYYY-MM-DD'); // 初始化 newTime
  
    state.formState.newAddress = [
      pu_province_id + '',
      pu_city_id + '',
      pu_district_id + '',
    ];
  
    pu_order_screenshot.split(',').map((item) => {
      state.imgList.push(item);
    });
  
    publishListMethod().then((res) => {
      state.platformData = res;
    });
  
    if (uploadRef.value) {
      uploadRef.value.initializeFileList();
    }
    spinning.value = false
  });
  
  const disabledDate = (current: Dayjs) => {
    return current && current < dayjs().endOf('day');
  };
  </script>
  
  <style lang="scss" scoped>
  .form_box {
    max-width: 800px;
    margin: 0 auto;
    padding: 0 30px;
  
    .header {
      margin: 30px 0;
    }
  }
  
  .ant-upload-text {
    width: 128px;
    height: 128px;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 2px solid #eee;
    border-radius: 20px;
  }
  </style>
  